package com.sx.zongzhi.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.Spinner;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.compress.Luban;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.sx.zongzhi.BaseActivity;
import com.sx.zongzhi.R;
import com.sx.zongzhi.adapter.HouseTypeAdapter;
import com.sx.zongzhi.adapter.SpinnerPubAdapter;
import com.sx.zongzhi.bean.GlobalBean;
import com.sx.zongzhi.bean.HouseBean;
import com.sx.zongzhi.bean.MsgEvent;
import com.sx.zongzhi.bean.PhotoBean;
import com.sx.zongzhi.bean.PublicBean;
import com.sx.zongzhi.net.ServiceFactory;
import com.sx.zongzhi.presenter.AddFactHousePest;
import com.sx.zongzhi.presenter.PublicListPest;
import com.sx.zongzhi.presenter.UploadFilePest;
import com.sx.zongzhi.utils.BaseUtil;
import com.sx.zongzhi.utils.MyRxBus;
import com.sx.zongzhi.utils.ToastUtils;
import com.sx.zongzhi.view.CommentView;
import com.sx.zongzhi.view.IPublicBeanView;
import com.sx.zongzhi.view.UploadFileView;
import com.sx.zongzhi.widget.LoadDialog;
import com.sx.zongzhi.widget.NoScrollGridView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by admin on 2017/12/18.
 */

public class UpdateFactHouseActivity extends BaseActivity implements IPublicBeanView, CommentView, UploadFileView {
    @BindView(R.id.gridView)
    NoScrollGridView gridView;
    @BindView(R.id.sp_houseUses)
    Spinner spHouseUses;
    @BindView(R.id.sp_certificateType)
    Spinner spCertificateType;
    @BindView(R.id.rl_address)
    RelativeLayout rlAddress;
    @BindView(R.id.rl_community)
    RelativeLayout rlCommunity;
    @BindView(R.id.rl_block)
    LinearLayout rlBlock;
    @BindView(R.id.imv_Head)
    ImageView imvHead;
    @BindView(R.id.et_address)
    EditText etAddress;
    @BindView(R.id.et_community)
    EditText etCommunity;
    @BindView(R.id.et_block)
    EditText etBlock;
    @BindView(R.id.et_unit)
    EditText etUnit;
    @BindView(R.id.et_room)
    EditText etRoom;
    @BindView(R.id.et_houseArea)
    EditText etHouseArea;
    @BindView(R.id.et_certificateNumbe)
    EditText etCertificateNumbe;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.et_propertyPersonMobile)
    EditText etPropertyPersonMobile;
    @BindView(R.id.et_propertyPersonTel)
    EditText etPropertyPersonTel;
    @BindView(R.id.et_nowLiveAddress)
    EditText etNowLiveAddress;
    @BindView(R.id.rg_isRentalHouse)
    RadioGroup rgIsRentalHouse;
    @BindView(R.id.rbt_Yes)
    RadioButton rbtYes;
    @BindView(R.id.rbt_No)
    RadioButton rbtNo;

    private boolean isBusiness = true, isRentalHouse = true;//是否商品房 是否出租房
    private String id, addressTypeId = "", address = "", community = "", block = "", unit = "", room = "",
            houseUsesId = "", houseArea = "", certificateTypeId = "", certificateNumbe = "", name = "",
            propertyPersonMobile = "", propertyPersonTel = "", nowLiveAddress = "",filePath = "";

    /**
     * 现居住址类型 证件代码 社会关注程度 安全隐患类型
     */
    private PublicListPest publicListPest;

    private List<GlobalBean> addressType;
    private List<GlobalBean>  houseUses;
    private List<GlobalBean>  certificateType;
    private HouseBean houseBean;

    @Override
    public void setUI(Bundle savedInstanceState) {
        setContentView(R.layout.activity_add_fact_house);
        setTitleName("实有房屋修改");
        setTitleRight("保存");
        ButterKnife.bind(this);
        houseBean = (HouseBean) getIntent().getSerializableExtra("houseBean");
        id = houseBean.getId();
        initData();
        rgIsRentalHouse.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                if (checkedId == R.id.rbt_Yes) {
                    isRentalHouse = true;
                } else {
                    isRentalHouse = false;
                }
            }
        });
        publicListPest = new PublicListPest(this);
        publicListPest.getPublicList("现居住址类型");
        publicListPest.getPublicList("证件代码");
        publicListPest.getPublicList("房屋用途");
    }

    private void initData() {
        RequestOptions options = new RequestOptions().centerCrop()
                .placeholder(R.mipmap.img_deful_house)
                .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                .error(R.mipmap.img_deful_house);
        Glide.with(this)
                .load(ServiceFactory.NEW_API_BASE_URL + File.separator + houseBean.getImgUrl())
                .apply(options)
                .into(imvHead);
        if (houseBean.getAddressType() != null && houseBean.getAddressType().getDisplayName().equals("商品房")) {
            rlCommunity.setVisibility(View.VISIBLE);
            rlBlock.setVisibility(View.VISIBLE);
            rlAddress.setVisibility(View.GONE);
            isBusiness = true;
            etCommunity.setText(houseBean.getCommunity());
            etBlock.setText(houseBean.getBlock());
            etUnit.setText(houseBean.getUnit());
            etRoom.setText(houseBean.getRoom());
        } else {
            isBusiness = false;
            etAddress.setText(houseBean.getAddress());
            rlCommunity.setVisibility(View.GONE);
            rlBlock.setVisibility(View.GONE);
            rlAddress.setVisibility(View.VISIBLE);
        }
        etHouseArea.setText(houseBean.getHouseArea() > 0 ? houseBean.getHouseArea() + "" : "");
        etCertificateNumbe.setText(BaseUtil.isEmpty(houseBean.getCertificateNumbe()) ? "" : houseBean.getCertificateNumbe());
        etName.setText(BaseUtil.isEmpty(houseBean.getName()) ? "" : houseBean.getName());
        etPropertyPersonMobile.setText(BaseUtil.isEmpty(houseBean.getPropertyPersonMobile()) ? "" : houseBean.getPropertyPersonMobile());
        etPropertyPersonTel.setText(BaseUtil.isEmpty(houseBean.getPropertyPersonTel()) ? "" : houseBean.getPropertyPersonTel());
        etNowLiveAddress.setText(BaseUtil.isEmpty(houseBean.getNowLiveAddress()) ? "" : houseBean.getNowLiveAddress());
        isRentalHouse = houseBean.isRentalHouse();
        if (isRentalHouse) {
            rbtYes.setChecked(true);
        }else {
            rbtNo.setChecked(true);
        }
    }

    @Override
    public void getPublicList(PublicBean publicBean) {
        if ("现居住址类型".equals(publicBean.getDomainName())) {
            addressType = publicBean.getDicts();
            if (addressType != null && addressType.size() > 0) {
                for (GlobalBean bean : addressType) {
                    if (bean.getId().equals(houseBean.getAddressType().getId())) {
                        addressTypeId = bean.getId();
                        bean.setSelect(true);
                    } else {
                        bean.setSelect(false);
                    }
                }
                final HouseTypeAdapter adapter = new HouseTypeAdapter(this, R.layout.item_facthouse, addressType);
                gridView.setAdapter(adapter);
                adapter.getEventType(new HouseTypeAdapter.EventTypeCallback() {
                    @Override
                    public void getData(GlobalBean typesBean) {
                        for (GlobalBean bean : addressType) {
                            bean.setSelect(false);
                        }
                        typesBean.setSelect(true);
                        addressTypeId = typesBean.getId();
                        adapter.notifyDataSetChanged();
                        if (typesBean.getDisplayName().equals("商品房")) {
                            isBusiness = true;
                            rlCommunity.setVisibility(View.VISIBLE);
                            rlBlock.setVisibility(View.VISIBLE);
                            rlAddress.setVisibility(View.GONE);
                        } else {
                            isBusiness = false;
                            rlCommunity.setVisibility(View.GONE);
                            rlBlock.setVisibility(View.GONE);
                            rlAddress.setVisibility(View.VISIBLE);
                        }
                    }
                });
            }
        }
        if ("证件代码".equals(publicBean.getDomainName())) {
            certificateType = publicBean.getDicts();
            if (certificateType != null && certificateType.size() > 0) {
                SpinnerPubAdapter adapter = new SpinnerPubAdapter(this, R.layout.item_text, certificateType);
                spCertificateType.setAdapter(adapter);
                if (houseBean.getCertificateType() != null){
                    showCertificateType();
                }
            }
        }
        if ("房屋用途".equals(publicBean.getDomainName())) {
            houseUses = publicBean.getDicts();
            if (houseUses != null && houseUses.size() > 0) {
                SpinnerPubAdapter adapter = new SpinnerPubAdapter(this, R.layout.item_text, houseUses);
                spHouseUses.setAdapter(adapter);
                if (houseBean.getHouseUses() != null){
                    showHouseUses();
                }
            }
        }
    }
    private void showCertificateType() {
        for (int i=0;i<certificateType.size();i++){
            if (certificateType.get(i).getId().equals(houseBean.getCertificateType().getId()) ){
                spCertificateType.setSelection(i);
            }
        }
    }
    private void showHouseUses() {
        for (int i=0;i<houseUses.size();i++){
            if (houseUses.get(i).getId().equals(houseBean.getHouseUses().getId())){
                spHouseUses.setSelection(i);
            }
        }
    }
    @OnClick({R.id.tv_right,R.id.imv_Head})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.tv_right:
                isCanLoad = true;
                subMit();
                if (isCanLoad){
                    LoadDialog.show(UpdateFactHouseActivity.this, "修改中...");
                    if (!BaseUtil.isEmpty(filePath)){
                        List<File> files = new ArrayList<>();
                        files.add(new File(filePath));
                        new UploadFilePest(this).uploadFile(this,files);
                    }else {
                        commitData("");
                    }
                }
                break;
            case R.id.imv_Head:
                PictureSelector.create(this)
                        .openGallery(PictureMimeType.ofImage())
                        .selectionMode(PictureConfig.SINGLE)
                        .maxSelectNum(1)
                        .previewImage(true)// 是否可预览图片
                        .enableCrop(true)
                        .compress(true)
                        .compressGrade(Luban.CUSTOM_GEAR)
                        .compressMaxKB(200)//压缩最大值kb compressGrade()为Luban.CUSTOM_GEAR有效 int
                        .forResult(PictureConfig.CHOOSE_REQUEST);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                List<LocalMedia> picUrls = PictureSelector.obtainMultipleResult(data);
                if (!picUrls.isEmpty()) {
                    for (LocalMedia localMedia : picUrls) {
                        filePath = localMedia.getCompressPath();
                        RequestOptions options = new RequestOptions().centerCrop()
                                .placeholder(R.drawable.shape_ff9f9f_12bgd)
                                .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                                .error(R.drawable.shape_ff9f9f_12bgd);
                        Glide.with(this)
                                .load(filePath)
                                .apply(options)
                                .into(imvHead);
                    }
                }
            }
        }
    }

    private boolean isCanLoad = true;
    private void subMit() {
        if (BaseUtil.isEmpty(addressTypeId)) {
            ToastUtils.showToast(UpdateFactHouseActivity.this, "请选择房屋类型");
            isCanLoad = false;
            return;
        }
        if (isBusiness) {
            community = etCommunity.getText().toString().trim();
            if (BaseUtil.isEmpty(community)) {
                etCommunity.setError("请填写小区名称");
                isCanLoad = false;
                return;
            }
            if (community.length() > 50) {
                etCommunity.setError("长度不能大于50个字符");
                isCanLoad = false;
                return;
            }
            block = etBlock.getText().toString().trim();
            if (BaseUtil.isEmpty(block)) {
                etBlock.setError("请填写第几幢");
                isCanLoad = false;
                return;
            }
            if (block.length() > 10) {
                etBlock.setError("长度不能大于10个字符");
                isCanLoad = false;
                return;
            }
            unit = etUnit.getText().toString().trim();
            if (BaseUtil.isEmpty(unit)) {
                etUnit.setError("请填写单元名称");
                isCanLoad = false;
                return;
            }
            if (unit.length() > 5) {
                etUnit.setError("长度不能大于5个字符");
                isCanLoad = false;
                return;
            }
            room = etRoom.getText().toString().trim();
            if (BaseUtil.isEmpty(room)) {
                etRoom.setError("请填写室名称");
                isCanLoad = false;
                return;
            }
            if (room.length() > 5) {
                etRoom.setError("长度不能大于5个字符");
                isCanLoad = false;
                return;
            }
        } else {
            address = etAddress.getText().toString().trim();
            if (BaseUtil.isEmpty(address)) {
                etAddress.setError("请填写房屋详址");
                isCanLoad = false;
                return;
            }
            if (address.length() > 100) {
                etAddress.setError("长度不能大于100个字符");
                isCanLoad = false;
                return;
            }
        }
        GlobalBean hou = (GlobalBean) spHouseUses.getSelectedItem();
        houseUsesId = hou.getId();

        houseArea = etHouseArea.getText().toString().trim();
        if (!BaseUtil.isEmpty(houseArea) && houseArea.length() > 11) {
            etHouseArea.setError("长度不能大于11个字符");
            isCanLoad = false;
            return;
        }
        GlobalBean CertificateType =  (GlobalBean) spCertificateType.getSelectedItem();
        certificateTypeId = CertificateType.getId();
        if (BaseUtil.isEmpty(certificateTypeId)) {
            ToastUtils.showToast(UpdateFactHouseActivity.this, "请选择证件代码");
            isCanLoad = false;
            return;
        }
        certificateNumbe = etCertificateNumbe.getText().toString().trim();
        if (BaseUtil.isEmpty(certificateNumbe)) {
            etCertificateNumbe.setError("请输入证件号码");
            isCanLoad = false;
            return;
        }
        if (certificateNumbe.length() > 30) {
            etCertificateNumbe.setError("长度不能大于30个字符");
            isCanLoad = false;
            return;
        }
        name = etName.getText().toString().trim();
        if (BaseUtil.isEmpty(name)) {
            etName.setError("请输入房主姓名");
            isCanLoad = false;
            return;
        }
        if (name.length() < 2 || name.length() > 30) {
            etName.setError("长度小于2个或大于30个字符");
            isCanLoad = false;
            return;
        }
        propertyPersonMobile = etPropertyPersonMobile.getText().toString().trim();
        propertyPersonTel = etPropertyPersonTel.getText().toString().trim();
        if (BaseUtil.isEmpty(propertyPersonMobile) && BaseUtil.isEmpty(propertyPersonTel)) {
            etPropertyPersonMobile.setError("请输入房主联系方式");
            isCanLoad = false;
            return;
        }
        if (!BaseUtil.isMobile(propertyPersonMobile)) {
            etPropertyPersonMobile.setError("请输入正确手机号");
            isCanLoad = false;
            return;
        }
        if (propertyPersonTel.length() > 15) {
            etPropertyPersonTel.setError("长度不能大于15个字符");
            isCanLoad = false;
            return;
        }
        nowLiveAddress = etNowLiveAddress.getText().toString().trim();
        if (BaseUtil.isEmpty(nowLiveAddress)) {
            etNowLiveAddress.setError("请输入房主现居住详址");
            isCanLoad = false;
            return;
        }
        if (nowLiveAddress.length() > 100) {
            etNowLiveAddress.setError("长度不能大于100个字符");
            isCanLoad = false;
            return;
        }
    }
    @Override
    public void commentSuccess(Boolean result) {
        LoadDialog.dismiss(UpdateFactHouseActivity.this);
        MyRxBus.get().post(new MsgEvent("FactHouseDetailActivity", 1, null));
        MyRxBus.get().post(new MsgEvent("FactHouseActivity", 1, null));
        MyRxBus.get().post(new MsgEvent("RentHouseActivity", 1, null));
        ToastUtils.showToast(this, "修改成功");
        finish();
    }
    @Override
    public void showError(String message) {
        LoadDialog.dismiss(UpdateFactHouseActivity.this);
        ToastUtils.showToast(this, message);
    }

    @Override
    public void uploadSuccess(List<PhotoBean> beans) {
        commitData(beans.get(0).getPath());
    }
    private void commitData(String urlPath) {
        new AddFactHousePest(this).updateFactHouse(this, id, addressTypeId, address, community, block, unit, room,
                houseUsesId, houseArea, certificateTypeId, certificateNumbe, name,
                propertyPersonMobile, propertyPersonTel, nowLiveAddress, isRentalHouse,urlPath);
    }

}
